package com.example.hello.service;

import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.util.UUID;

@Service
public class FileService {
    
    private static final Logger log = LoggerFactory.getLogger(FileService.class);
    
    @Value("${minio.bucket}")
    private String bucketName;
    
    @Value("${minio.external-endpoint}")
    private String externalEndpoint;
    
    @Autowired
    private MinioClient minioClient;

    /**
     * 上传 MultipartFile 文件
     */
    public String uploadFile(MultipartFile file) throws Exception {
        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;
            
            // 上传文件到对象存储
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            
            // 返回文件访问路径
            return String.format("%s/%s/%s", externalEndpoint, bucketName, objectName);
            
        } catch (Exception e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败");
        }
    }
    
    /**
     * 上传字节数组
     * @param bytes 文件字节数组
     * @param fileName 文件名
     * @param contentType 文件类型
     * @return 文件访问路径
     */
    public String uploadBytes(byte[] bytes, String fileName, String contentType) throws Exception {
        try {
            log.info("开始上传字节数组: fileName={}, contentType={}, size={}字节", 
                     fileName, contentType, bytes.length);
                     
            // 确保文件名不重复
            String objectName = "images/" + UUID.randomUUID().toString() + 
                              fileName.substring(fileName.lastIndexOf("."));
            
            // 上传字节数组
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(new ByteArrayInputStream(bytes), bytes.length, -1)
                    .contentType(contentType)
                    .build());
            
            // 返回文件URL
            String fileUrl = String.format("%s/%s/%s", externalEndpoint, bucketName, objectName);
            log.info("字节数组上传成功: {}", fileUrl);
            return fileUrl;
            
        } catch (Exception e) {
            log.error("字节数组上传失败: {}", e.getMessage(), e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }
} 